//
//  ViewController.m
//  ZGSHGYS
//
//  Created by hnb on 2016/11/18.
//  Copyright © 2016年 yncc. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>

#define BaseUrl    @"http://shihu.ynccxx.com/mobile/"
#define UPLOADURL     @"http://shihu.ynccxx.com/api/avatar/upload.php"
@interface ViewController ()<WKNavigationDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,WKScriptMessageHandler>
@property (nonatomic,strong) WKWebView *webView;
@property (nonatomic,strong) MBProgressHUD *hud;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.preferences.minimumFontSize = 18;
    _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) configuration:config];
    _webView.scrollView.showsVerticalScrollIndicator = NO;
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    _webView.navigationDelegate = self;
    _webView.allowsBackForwardNavigationGestures = YES;
    _webView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_webView];
    WKUserContentController *userCC = config.userContentController;
    [userCC addScriptMessageHandler:self name:@"upload"];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:BaseUrl] cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:10.0]];

    
}
-(MBProgressHUD *)hud{
    if (!_hud) {
        _hud = [MBProgressHUD showHUDAddedTo:self.webView animated:YES];
    }
    return _hud;
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
     self.hud.label.text = @"加载数据中";
    
    NSString *path=[webView.URL absoluteString];
    NSString * newPath = [path lowercaseString];
    NSLog(@"newPath%@",newPath);
    if ([newPath hasPrefix:@"sms:"] || [newPath hasPrefix:@"tel:"]) {
        UIApplication * app = [UIApplication sharedApplication];
        if ([app canOpenURL:[NSURL URLWithString:newPath]]) {
            [app openURL:[NSURL URLWithString:newPath]];
        }
        return;
    }
    
//    [self.webView evaluateJavaScript:@"uploaduserhead()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//        //TODO
//        NSLog(@"%@ %@",response,error);
//    }];
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
        [_hud hideAnimated:YES];
//    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//    
//    
//    context[@"uploaduserhead"] = ^() {
//        
//        NSArray *args = [JSContext currentArguments];
//        for (JSValue *jsVal in args) {
////            //                NSLog(@"---%@", jsVal);
////            _identify = [NSString stringWithFormat:@"%@",jsVal];
//        }
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self toUplodePhoto];
//        });
//    };
//    context[@"loadHead"] = ^() {
//        
//        NSArray *args = [JSContext currentArguments];
//        for (JSValue *jsVal in args) {
//            _identify = [NSString stringWithFormat:@"%@",jsVal];
//        }
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self toUplodePhoto];
//        });
//    };

}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    self.hud.label.text = @"加载失败";
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        [self doSomeWork];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.hud hideAnimated:YES];
        });
    });
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"upload"]) {
        [self toUplodePhoto];
    }
}

-(void)toUplodePhoto{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancleAlert = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *photoAlert = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"拍照");
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *imagepicker = [[UIImagePickerController alloc] init];
            imagepicker.delegate = self;
            //设置数据源类型
            imagepicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            imagepicker.allowsEditing = YES;
            [self presentViewController:imagepicker animated:YES completion:nil];
        }else{
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"此设备暂不支持拍照" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancleAlert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
            [alertVC addAction:cancleAlert];
            [self presentViewController:alertVC animated:YES completion:nil];
        }
    }];
    UIAlertAction *photoAlbumAlert = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"从相册选择");
        UIImagePickerController *imagepicker = [[UIImagePickerController alloc] init];
        imagepicker.delegate = self;
        imagepicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagepicker.allowsEditing = YES;
        [self presentViewController:imagepicker animated:YES completion:nil];
        
        
    }];
    [alertVC addAction:cancleAlert];
    [alertVC addAction:photoAlert];
    [alertVC addAction:photoAlbumAlert];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
//    [self postImageToSever:image];//进行上传图片操作
    
    [self uploadImgToService:image];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
/**
 *  上传图片到服务器
 */
-(void)uploadImgToService:(UIImage *)image{
    NSData *data = UIImageJPEGRepresentation(image, 0.7);
    NSString *urlstr =  @"http://shihu.ynccxx.com/api/avatar/upload.php";
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    NSDictionary *paramter = @{};
     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager POST:urlstr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            [formData appendPartWithFileData:data name:@"pic" fileName:@"pic.png" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
//    [manager GET:urlstr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@",responseObject);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//    }];
//        paramter = @{@"ext": @"png"};
//    [manager GET:urlstr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
////        [formData appendPartWithFileData:data name:@"pic" fileName:@"pic" mimeType:@"image/png"];
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        self.hud.label.text = @"上传照片中。。";
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        [self.hud hideAnimated:YES];
//        NSLog(@"%@",responseObject);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//             [self.hud hideAnimated:YES];
//    }];
}

//- (void)postImageToSever:(UIImage *)image{
//    
//
//    
//    //下载管理类的对象
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    // 设置时间格式
//    formatter.dateFormat = @"yyyyMMddHHmmss";
//    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
//    NSString *fileName = [NSString stringWithFormat:@"%@.png", dateStr];
//    
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    
//    NSData *imgData=UIImagePNGRepresentation(image);
//    
//    
//    params[@"img"] = imgData;
//    params[@"title"] = fileName;
//    
//    //默认传输的数据类型是二进制
//    
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    
//    //第三个参数：进行上传数据的保存操作
//    
//    [manager POST:REQUEST_SERVER_URL parameters:params constructingBodyWithBlock:^(id formData) {
//        
//        [formData appendPartWithFileData:imgData name:@"img" fileName:fileName mimeType:@"image/png"];
//        [self MBPRogressPageView];
//        
//    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        
//        
//        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//        
//        NSLog(@"success %@",str);
//        NSDictionary *allDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
//        NSDictionary *dataDic = [allDic valueForKey:@"data"];
//        
//        self.imageUrl = [dataDic valueForKey:@"img"];
//        NSString *_imgId = [dataDic valueForKey:@"id"];
//        
//        //        更新图片
//        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showHead('%@','%@','%@');",_imageUrl,_identify,_imgId]];
//        
//        
//        
//        //    进度环
//        _progressHud.hidden = YES;
//        [_progressHud removeFromSuperview];
//        _progressHud = nil;
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//        NSLog(@"error %@",error.description);
//        //    进度环
//        _progressHud.hidden = YES;
//        [_progressHud removeFromSuperview];
//        _progressHud = nil;
//        
//    }];
//    
//    
//}
- (void)doSomeWork {
    // Simulate by just waiting.
    sleep(3.);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
